import { FairyGUI , System } from 'csharp';
import FairyUtils from '../../com/utils/FairyUtils';
/*
 *
 *@author clong 2020.11.01
 */
export default class BaseButton extends FairyGUI.GButton {

    protected _data = null;
    protected btns:Array<FairyGUI.GButton> = [];
    /**是否已初始化 */
    protected isInit:boolean = false;
    /**ICON */
    protected _iconObject:FairyGUI.GLoader;

    constructor() {
        super();
        Object.defineProperty(this, "data", {
            set:function(data){
                this.show( data );
            },
            get: function () { 
                return this._data;
            }
        });
        this.__onConstruct = () => { this.onConstruct(); };
    }

    protected setVar():void{

        // console.log("---------->setVar");
        FairyUtils.setVar( this , this , this.btns );
        // this.onCallBtns(); 
        this.isInit = true;
        this.initUI();
        this.show(this._data);
    }

    private onConstruct():void{

        this.setVar();
        // console.log("---------->onConstruct this.btns.length: " + this.btns.length );        
    }

    initUI():void{

        this._iconObject = this.GetChild("icon") && this.GetChild("icon").asLoader;
    }

    show( data:any ):void{

        this._data = data;
        this.visible = true;
        if( this.isInit ){
            this.onCallBtns();
            this.AddListener();
        }
    }

    public AddListener():void{


    }

    public RemoveListener():void{

        
    }

    protected onCallBtns():void{

        let btn:FairyGUI.GButton;
        for( btn of this.btns ){
            if(!btn) continue;
            let callback1 = (context:FairyGUI.EventContext)=>{
                this.onBtnClick( context.sender as FairyGUI.GButton );
            }
            btn && btn.onClick.Clear();
            btn && btn.onClick.Add( callback1 );
            this[btn.name + "_EventCallBack"] = callback1;
        }
    }

    onBtnClick( btn:any ):void{ 
        
    }

    /**
     * 获取对应父容器的类对象
     * @param cls 
     * @param self 
     */
    public getParentOf( cls:any , self:any = null ):any{

        var parent:any = self ? self.parent : this.parent;
        var p:any = null;
        if( parent != null ){
            if( parent instanceof cls ){
                return parent;
            }else{
                return this.getParentOf( cls , parent );
            }            
        }
        return null;
    }

    hide():void{ 
        let btn:FairyGUI.GButton;
        for( btn of this.btns ){
            let callback1 = this[btn.name + "_EventCallBack"];
            btn && callback1 && btn.onClick.Clear();
            btn && callback1 && btn.onClick.Remove( callback1 );
        }
        this.visible = false;
        this.RemoveListener();
    }
}